{% extends 'base/userinfo.html' %}


{% block head %}
<meta charset="utf-8">
<title>salt部署配置 管理界面</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/asset/layui/css/layui.css" media="all">
<link rel="stylesheet" href="/asset/css/global.css" media="all">
<script src="/asset/js/js-yaml.min.js"></script>
<script src="/asset/js/util.js" charset="utf-8"></script>

<style>
    .layui-body {
        left: 30px !important;
    }

    .e {
        height: 600px;
        min-width: 1000px;
        font-size: 14px;
    }

    .btn_slected {
        background-color: #FFB800 !important;
    }

    .del {
        padding: 0 !important;
    }

</style>

{% endblock %}

{% block body %}


<div id="box" style="display: none">
    <h1 class="site-h1"></h1>

    <form class="layui-form" action="" id="item-form">

        <div class="layui-form-item">
            <label class="layui-form-label">app_name</label>

            <div class="layui-input-block">
                <input type="text" name="app_name" autocomplete="off" placeholder="" class="layui-input ">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">步骤</label>

            <div class="layui-input-block" id="btn_groups">

                <button class="layui-btn layui-btn-normal layui-btn-sm" id="add_deploy">
                    <i class="layui-icon">&#xe654;</i>
                </button>

            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">命令</label>

            <div class="layui-input-block">
                <textarea name="execmd" cols="30" rows="10" class="layui-textarea" id="execmd"></textarea>

            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="demo1" id="submit_add">立即提交</button>

            </div>
        </div>

    </form>
</div>

<div class="layui-body">

    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li><a href="salt-run.html">线上部署</a></li>

            <li class="layui-this"><a href="salt-run-config.html">salt部署配置</a></li>

        </ul>
        <div class="layui-tab-content"></div>
    </div>


    <h1 class="site-h1">salt部署配置 </h1>

    <table class="layui-table"
           lay-data="{ height: 'full', url:'/salt_run_config_list', page:true, id:'idTest', limit: 20,}"
           lay-filter="demo">
        <thead>
        <tr>
            <th lay-data="{field:'app_name', sort: true, fixed: true}">应用名称</th>
            <th lay-data="{field:'remark', sort: true, fixed: true}">应用描述</th>

            <th lay-data="{fixed: 'right', align:'center', toolbar: '#barDemo'}">部署配置</th>
            <th lay-data="{fixed: 'right', align:'center', toolbar: '#misc'}">其他配置</th>

        </tr>
        </thead>
    </table>

</div>


<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-normal layui-btn-sm " lay-event="execmd">配置</a>
</script>


<script type="text/html" id="misc">
    <a class="layui-btn layui-btn-normal layui-btn-sm " lay-event="misc">配置</a>

</script>


<script type="text/html" id="logstash">
</script>

<script src="/asset/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
<script>
    layui.use(['table', "form"], function () {
        var $ = layui.$

        var group_list = []

        var table = layui.table;
        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj)
        });


        //监听工具条
        table.on('tool(demo)', function (obj) {
            if (['misc', "execmd"].indexOf(obj.event) >= 0) {
                edit_item_by_name(obj.data, obj.event)
            }
        });


        var index = null

        var deploy_data = []
        var deploy_data_kv = {}

        var gexc_name = 0  // 0 未初始化, 1 测试 2 正式
        var current_deploy_name = ""


        function edit_item_by_name(data, exc_name) {
            {
                deploy_data = (data[exc_name] && data[exc_name][0]) ? data[exc_name] : [];
                gexc_name = exc_name
            }
//            debugger
            index = layer.open({
                type: 1,
                title: '编辑: ' + exc_name,              // [可选]
                content: $('#box'),          // 对话框中的内容部分
                area: ['1200px', '800px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            render_form($("#item-form"), data)
            form.render()
            render_deploy_btn(deploy_data)

        }


        var form = layui.form

        //监听提交
        form.on('submit(demo1)', function (data) {
            update_exc()

            var _data = {}
            _data['app_name'] = data.field['app_name']

            _data[gexc_name] = deploy_data
            $.ajax({
                url: "/salt_run_config",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(_data),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('提交失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false
                    }
                    layer.msg('更新成功');
                    layer.close(index)
//                    table.reload('idTest', {});
                    location.reload()
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });


        $("body").delegate("#add_deploy", 'click', function (event) {
            event.preventDefault()

            layer.prompt({title: '新建部署步骤', formType: 0}, function (key, index) {
                for (ii in deploy_data) {
                    if (deploy_data[ii][0] == key) {
                        layer.msg("步骤名称重复");

                        return
                    }
                }
                layer.close(index);
                deploy_data.push([key, ""])
                render_deploy_btn(deploy_data)
            });
        })

        function update_exc() {

            /// update exc
            var exc = $("#execmd").val()
            deploy_data_kv[current_deploy_name] = exc
            var ii = 0
            for (ii in deploy_data) {
                if (deploy_data[ii][0] == current_deploy_name) {
                    deploy_data[ii][1] = exc
                    break
                }
            }
            /// end update exc

        }

        $("#btn_groups").delegate("button", "click", function (e) {
            e.preventDefault()

            update_exc()

            var $el = $(e.currentTarget)
            var id = $el.attr("id")
            if (id.indexOf("del_") == 0) {  //删除按钮
                var key = id.substr(4)
                $("#btn_groups").find("#wrap_" + key).remove()

                var ii = 0
                for (ii in deploy_data) {
                    if (deploy_data[ii][0] == key) {
                        break
                    }
                }
                deploy_data.splice(ii)
            } else if (id != "add_deploy") {
//                debugger

                var _deploy_exc = deploy_data_kv[id]
                $("#execmd").val(_deploy_exc)

                $("#" + current_deploy_name).removeClass("btn_slected")
                $("#" + id).addClass("btn_slected")
                current_deploy_name = id
            }

        })

        function render_deploy_btn(_deploy_data) {

            current_deploy_name = _deploy_data[0] ? _deploy_data[0][0] : ""

            deploy_data_kv = {}

            var _html = ""
            for (var ii in _deploy_data) {
                var deploy = _deploy_data[ii]
                var _deploy_name = deploy[0]
                var _deploy_exc = deploy[1]

                deploy_data_kv[_deploy_name] = _deploy_exc  // 同步kv

                _html += '\
                  <div class="layui-btn-group" id="wrap_' + _deploy_name + '">\
                    <button class="layui-btn ' + ( ii == 0 ? "btn_slected" : "") + '" id="' + _deploy_name + '">' + _deploy_name + '</button>\
                    <button class="layui-btn layui-btn-danger  del" id="del_' + _deploy_name + '">\
                        <i class="layui-icon">&#xe640;</i>\
                    </button>\
                </div>'

            }

            _html += '\
                <button class="layui-btn layui-btn-normal layui-btn-sm" id="add_deploy">\
                    <i class="layui-icon">&#xe654;</i>\
                </button> '

            $("#btn_groups").empty()
            $("#btn_groups").append(_html)


            var _deploy_exc = deploy_data_kv[current_deploy_name]
            $("#execmd").val(_deploy_exc)

        }

    });

    function render_form($form, row) {
        if (!row) {
            $form.find('input').val("");
            $form.find('select').val("");
            $form.find('textarea').val("");
            return
        }
        for (var name in row) {
            $form.find('input[name="' + name + '"]').val(row[name]);
            $form.find('select[name="' + name + '"]').val(row[name]);
            $form.find('textarea[name="' + name + '"]').val(row[name]);
        }

    }
</script>
{% endblock %}
